<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\constant\v1\CommonConstant;
use plugin\admin\app\model\Admin;
use plugin\admin\app\service\v1\SmsService;
use support\Request;
use support\Response;
use plugin\admin\app\model\V1Sms;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 短信记录
 */
class V1SmsController extends Crud
{
    /**
     * 无需登录及鉴权的方法
     * @var array
     */
    protected $noNeedLogin = ['send'];

    /**
     * 需要登录无需鉴权的方法
     * @var array
     */
    protected $noNeedAuth = [];

    /**
     * @var V1Sms
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new V1Sms;
    }

    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('v1-sms/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('v1-sms/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('v1-sms/update');
    }


    /**
     * 发送验证码
     * @param Request $request
     * @return Response
     * @throws BusinessException
     **/
    public function send(Request $request): Response
    {
        if ($request->method() === 'POST') {
            $mobile = $request->post('mobile');
            $event = $request->post('event');
            $event = $event ? $event : CommonConstant::SMS_0;
            if (!$mobile) {
                return $this->json(1,'请输入手机号！');
            }

            $last = SmsService::get($mobile, $event);
            if ($last) {
                $created_at = strtotime($last['created_at']);
                if (time() - $created_at < 60) {
                    return $this->json(1,'发送频繁！');
                }
            }
            $mobile_check = Admin::where('mobile', $mobile)->whereIn('user_status',[CommonConstant::DEFAULT_2])->first('id');
            if ($event == CommonConstant::SMS_0) {
                if ($mobile_check) {
                    return $this->json(1,'手机号码已被注册！');
                }
            }
            if ($event == CommonConstant::SMS_1) {
                if (!$mobile_check) {
                    return $this->json(1,'手机号码不存在！');
                }
            }
            $ret = SmsService::send($mobile, null, $event);
            return $this->json($ret['code'],$ret['msg']);
        }
    }

}
